import React, { Component} from 'react';
import { Route, Routes } from 'react-router-dom';
import { Button ,Tree , Dialog , Form ,Input,Message , MessageBox , Select,Tabs} from "element-react";
import Devicepage from '../Devicepage';
import Lendpage from '../Lendpage';
import Userpage from '../Userpage';
import PubSub from 'pubsub-js';
import './index.css';
import { store } from 'core-js/modules/_wks';
import Approverpage from '../Approverpage';
import MaintianPage from '../MaintainPage';
import DeviceStock from '../DeviceStock';
import { connect } from 'react-redux';
import {createLoginAction} from '../../redux/actions/loginAction'
import Orgpage from '../Orgpage';
import DeviceTree from '../DeviceTree';
import Processpage from '../Processpage';
import LendProcesspage from '../LendProcesspage';
import Repairpage from '../Repairpage';

function Theme(){
    return (
      <div className='device-content-background'></div>
    )
}

class DeviceManage extends Component {
  state = {
    currApprover:"",
    approverlist:[] ,
    dialogVisible: false,
    form: {
      label: '',
      type: ''
    },
    data: [],
    options: {
      children: 'children',
      label: 'label'
    },
  }

  netcontorll = new AbortController()

  componentDidMount(){
    //设备列表
   fetch("/device/devicebaiseinfo/devicelist")
    .then(data => data.json())
    .then(result=>{
      this.setState({data:result.data});
    })



    // 有权限的管理人员列表
    fetch("/device/userbaiseinfo/getapproverlist",{
      method:"POST",
      headers: {
        "Content-Type": "application/json",
        // "Content-Type": "application/x-www-form-urlencoded",
      },  
      body:JSON.stringify({role:2})
    })
    .then(data => data.json())
    .then(result=>{
      console.log(result.list)
      this.setState({approverlist:result.list});
    })
  }

  componentWillUnmount(){
    //防止组件加载网络还未出结果组件就被卸载了导致的异常
    this.netcontorll.abort()
  }

  append(store, data ) {
    MessageBox.msgbox({
      title: '添加设备类型',
      message: 
      ( <div>
            <Form model={this.state.form}>
              <Form.Item label="设备标签">
                <Input onChange={(e)=>{this.setState({form:{label:e , type:this.state.form.type}})}}></Input>
              </Form.Item>
              <Form.Item label="设备类型" >
              <Input   onChange={(e)=>{this.setState({form:{type:e , label:this.state.form.label}})}}></Input>
              </Form.Item>
            </Form>
        </div>
      )
      ,
      showCancelButton: true
    }).then(async action => {
      if(action==='confirm') {
        let el = {
          "label":this.state.form.label ,
          "level":data.level+1,
          "parent":data.id,
          "child":"0",
          "type":this.state.form.type
        }
        console.log(el)
        let id = await this.addDevice(el) ;
        // el.id = id ;
        // el.children = []
        // data.children = [...data.children , el]
        // store.getNode(data).expanded = store.getNode(data).expanded?true : false
      }

    })
  }
  addApprover =(result)=>{
    fetch("/device/devicemanageapprover/save",{
      method:"POST",
       headers: {
         "Content-Type": "application/json",
       },  
       body:JSON.stringify({
        typeid:result.id,
        approver:this.state.currApprover 
       })
    }).then(data=>data.json())
    .then(result=>{
      if(result.code===0) {
        Message({
          message: '审批人添加成功',
          type: 'success'
        });
      } else {
        Message({
          message: '添加失败',
          type: 'error'
        });
      }
    })
  }
  
  addDevice = async (data)=>{
    let id = await fetch("/device/devicebaiseinfo/save" , {
       method:"POST",
       headers: {
         "Content-Type": "application/json",
         // "Content-Type": "application/x-www-form-urlencoded",
       },  
       body:JSON.stringify(data)
     }).then(data =>data.json())
     .then(result =>{
       if(result.code===0) {
         //添加设备审批人
         if(data.level===0) {
          this.addApprover(result)
         }
         Message({
          message: '分类添加成功',
          type: 'success'
        });
       } else {
         Message({
           message: '添加失败',
           type: 'error'
         });
       }
       return result.id
     })
     if(data.level===0) {

      //  this.setState({data:[{id , label:this.state.form.label , children:[]},...this.state.data] , dialogVisible:false})
     }
     await fetch("/device/devicebaiseinfo/devicelist")
     .then(data => data.json())
     .then(result=>{
       this.setState({data:result.data,dialogVisible:false});
     })
     return id
   }



  remove = (nodeModel ,store, data )=> {

      MessageBox.confirm('是否删除分类?', '提示', {
        type: 'warning'
      }).then(() => {
        this.removeDevice(data.id , store ,data)
      }).catch(() => {
        Message({
          type: 'info',
          message: '已取消删除'
        });
      });
  } 
  refresh =()=>{
    fetch("/device/devicebaiseinfo/devicelist")
    .then(data => data.json())
    .then(result=>{
      this.setState({data:result.data});
    })
  }

  removeDevice = (ids , store , data )=>{
   fetch("/device/devicebaiseinfo/delete", {
      method:"POST",
      headers:{
        "Content-Type": "application/json",
      },
      body:JSON.stringify([ids])
    }).then(data=>data.json())
    .then(result =>{
        const {code} = result ;
        if(code === 0 ) {
          //更新方法，store.remove的操作可能是同步更新操作不是异步，或者说要在下一个this.setState() 操作才能再次更新操作，调用this.setState()的操作，将前面的更新操作移入更新队列，否则要会被阻塞住，看才来是这样的具体机制不清楚 -_-!
          store.remove(data)
          this.setState({})   
          Message({
            type: 'success',
            message: '删除成功!'
          });
        } else{
          Message({
            type: 'error',
            message: '删除失败'
          });
        }
    })
  }

  renderContent(nodeModel, data, store) {
    return (
      <span>
        <span>
          <span>{data.label}</span>
        </span>
        <span style={{float: 'right', marginRight: '130px'}}>
          <Button size="mini" onClick={ () => this.append(store, data) }>Append</Button>
          <Button size="mini" onClick={async () => {this.remove(nodeModel ,store, data)}} disabled={!nodeModel.isLeaf}>Delete</Button>
        </span>
      </span>);
  } 

  render() {
    
    const { data, options } = this.state
    return (
      <div>
        <Button onClick={()=>this.setState({dialogVisible:true})}>add</Button>
        <Dialog
          title="添加设备"
          visible={ this.state.dialogVisible }
          onCancel={ () => this.setState({ dialogVisible: false }) }
        >
          <Dialog.Body>
            <Form model={this.state.form}>
              <Form.Item label="设备标签" labelWidth="120">
                <Input onChange={(e)=>{this.state.form.label= e}}></Input>
              </Form.Item>
              <Form.Item label="设备类型" labelWidth="120">
                <Input   onChange={(e)=>{this.state.form.type = e}}></Input>
              </Form.Item>
              <Form.Item  label={"审批人"} labelWidth="120">
                <Select onChange={(e)=>{this.state.currApprover=e}} filterable={true}>
                  {
                    this.state.approverlist.map(el=>{
                      return (
                        <Select.Option
                          key={el.id}
                          label={el.name}
                          value={el.id}
                        />
                      )
                    })
                  }
                </Select>
              </Form.Item>
            </Form>
          </Dialog.Body>

          <Dialog.Footer className="dialog-footer">
            <Button style={{width:"auto"}} onClick={ () => this.setState({ dialogVisible: false }) }>取 消</Button>
            <Button style={{width:"auto"}} type="primary" onClick={ () =>{this.addDevice({
              "label":this.state.form.label ,
              "level":0,
              "parent":"0",
              "child":"0",
              "type":this.state.form.type
            })} }>确 定</Button>
          </Dialog.Footer>
        </Dialog>

        <Input placeholder="输入关键字进行过滤" onChange={text=> this.tree.filter(text)} />
        <Tree
          ref={e=> this.tree = e}
          data={data}
          options={options}
          isShowCheckbox={true}
          nodeKey="id"
          expandOnClickNode={true}
          renderContent={(...args)=>this.renderContent(...args)}
          filterNodeMethod={(value, data)=>{
            if (!value) return true;
            return data.label.indexOf(value) !== -1;
          }}
        />
      </div>
    )
  }
}



class ContentUI extends Component {

  meun= {
    1:{id : 1 ,title :"通用设置" ,name: "通用设置" , content:<div></div>},
    2:{id : 2 ,title :"人员设置" ,name: "人员设置" , content:<Userpage/>},
    3:{id : 3 ,title :"分类维护" ,name: "分类维护" , content:<DeviceManage/>},
    4:{id : 4 ,title :"设备管理" ,name: "设备管理" , content:<Devicepage/>},
    5:{id : 5 ,title :"维护计划" ,name: "维护计划" , content:<MaintianPage/>},
    6:{id : 6 ,title :"系统设置" ,name: "系统设置" , content:<div>系统设置</div>},
    7:{id : 7 ,title :"出借管理" ,name: "出借管理" , content:<Lendpage/>},
    8:{id : 8 ,title :"审批中心" ,name: "审批中心" , content:<Approverpage/>},
    9:{id : 9 ,title :"个人消息" ,name: "个人消息" , content:<div>个人消息中心</div>},
    10:{id : 10 ,title :"仓库管理" ,name: "仓库管理" , content:<DeviceStock/>},
    11:{id : 7 ,name  :"可视化" ,  title :"可视化" , connent:<DeviceTree/>}
  }


  componentWillUnmount(){
    PubSub.unsubscribe(this.pubsubid)
  }

  componentDidMount(){
    console.log(this.props.userInfo)
    const {role} = this.props.userInfo
    switch ( role ){
      case 4:
        this.state.tabsmate = [
          {id : 1 ,title :"人员设置" ,name: "人员设置" , content:<Userpage/>},
          {id : 2 ,title :"分类维护" ,name: "分类维护" , content:<DeviceManage/>},
          {id : 3 ,title :"设备管理" ,name: "设备管理" , content:<Devicepage/>},
          {id : 4 ,title :"维护计划" ,name: "维护计划" , content:<MaintianPage/>},
          {id : 5 ,title :"出借管理" ,name: "出借管理" , content:<LendProcesspage/>},
          {id : 6 ,name  :"组织管理" , title :"组织管理" , content:<Orgpage/>},
          {id : 7 ,name  :"流程管理" ,  title :"流程管理" , content:<DeviceTree/>},
          {id : 8 ,name  :"统一审批" ,  title :"统一审批" , content:<Processpage/>},
          {id : 9 ,title :"维修计划" ,name: "维修计划" , content:<Repairpage/>}
        ]
        break ;
      case 3 :
        this.state.tabsmate = [
          {id : 1 ,title :"仓库管理" ,name: "仓库管理" , content:<Processpage/>}
        ]
        break ;
      case 2 :
        this.state.tabsmate = [
          {id : 1 ,title :"出借管理" ,name: "出借管理" , content:<Lendpage/>},
          {id : 2 ,title :"审批中心" ,name: "审批中心" , content:<Approverpage/>},
          {id : 3 ,name  :"统一审批" ,  title :"统一审批" , content:<Processpage/>},
        ]
        break;
      case 1 :
        this.state.tabsmate = [
          {id : 1 ,title :"出借管理" ,name: "出借管理" , content:<LendProcesspage/>},
        ]
          break;
      default:
        break ;
    }
    this.setState({})
    this.pubsubid = PubSub.subscribe("addtabs",(msg , value)=>{
      let flag = true;
      console.log(this.state.tabsmate[value])
      const {tabs} = this.state
      tabs.map((item)=>{
        if(item.id===(value+1)) {
          flag = false ;
        }
      })
      if(flag) {
        this.setState({
          tabs:[this.state.tabsmate[value],...tabs],
          currTabs:this.state.tabsmate[value].name
        })
      } else {
        this.setState({
          currTabs:this.state.tabsmate[value].name
        })
      }
    })
  }

  

  state = {
    tabs: [],
    tabsmate: {

    },
    tabIndex: [],
    currTabs:" "
  }
  
  removeTab = (tab)=> {
    const { tabs, tabIndex } = this.state;
    tabs.splice(tab.key.replace(/^\.\$/, ''), 1);
    this.setState({
      tabs,
    });
  }


  render() { 
    return (
      <div className='device-content'>
          {/* <Routes>
            <Route  path='0' element={<div>122222222222222</div>}></Route>
            <Route  path='1' element={<Userpage/>}></Route>
            <Route  path='2' element={<DeviceManage/>}></Route>
            <Route  path='3' element={<Devicepage/>}></Route>
            <Route  path='4' element={<div>维护计划</div>}></Route>
            <Route  path='5' element={<div>系统设置</div>}></Route>
            <Route  path='6' element={<Lendpage/>}></Route>
            <Route  path='7' element={<Approverpage/>}></Route>
            <Route  path='8' element={<div>个人消息中心</div>}></Route>
            <Route  path='' element={<Theme/>}></Route>
          </Routes> */}
        <Tabs type="card" value={this.state.currTabs} onTabRemove={(tab) => this.removeTab(tab)} style={{height:"100%"}}>
          {
            this.state.tabs.map((item, index) => {
              return <Tabs.Pane key={index} style={{height:"100%"}} closable label={item.title} name={item.name}>{item.content}</Tabs.Pane>
            })
          }
        </Tabs>
      </div>
    )
  }
}
export default connect(
  state=>({userInfo:state.login}),
  {
    userlogin:createLoginAction
  }
)(ContentUI);